package com.myblockchain.p2p;

import com.myblockchain.utility.SpringUtil;
import com.myblockchain.service.P2PService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

/**
 * @author Liu
 */
@Component
@ClientEndpoint
public class P2PClient {

    @Autowired
    private P2PService p2PService;

    private Session session;

    public void connectToPeer(String url) throws IOException, DeploymentException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI uri = URI.create(url);
        this.session = container.connectToServer(P2PClient.class, uri);
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.sendMsg(session, p2PService.queryLatestBlockMsg());
        p2PService.sendMsg(session, p2PService.queryTransactionMsg());
        p2PService.sendMsg(session, p2PService.queryPackedTransactionMsg());
        p2PService.sendMsg(session, p2PService.queryWalletMsg());
        p2PService.addClient(session);
    }
    @OnMessage
    public void onMessage(String msg) {
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.handleMessage(this.session, msg);
    }
    @OnClose
    public void onClosing() throws IOException {
        session.close();
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.removeClient(this.session);
    }


    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.removeClient(this.session);
    }


}
